﻿using System;
using System.Reflection;

namespace DependencyAnalysis.Internal
{
    public static class ReflectionUtilities
    {
        private const int InterfaceMarker = ((int)MethodAttributes.Final | (int)MethodAttributes.Virtual | (int)MethodAttributes.VtableLayoutMask);
        private const int GeneratedMarker = ((int)MethodAttributes.Private | (int)MethodAttributes.Final | (int)MethodAttributes.Virtual | (int)MethodAttributes.VtableLayoutMask);

        public static bool IsMemberDefinedInInterface(MethodBase member)
        {
            return InterfaceMarker == ((int)member.Attributes & InterfaceMarker);
        }

        public static bool IsMemberOverride(MethodBase member)
        {
            var attributes = (int) member.Attributes;
            return ((attributes & (int) MethodAttributes.Virtual) == (int) MethodAttributes.Virtual) &&
                ((attributes & (int)MethodAttributes.VtableLayoutMask) == 0);
        }

        public static bool IsMemberGenerated(MethodBase member)
        {
            try
            {
                string name = member.ToString();
                return GeneratedMarker == ((int)member.Attributes & GeneratedMarker) ||
                    name.Contains("Void System.Windows.Markup.IComponentConnector")
                    || name.Contains("<PrivateImplementationDetails>");
            }
            catch (TypeLoadException)
            {
                
                return false;
            }
        }
    }
}
